import {Buffer} from "buffer";
import {Unsigned16} from "./Unsigned16";
import {Unsigned8} from "./Unsigned8";
import {AxdrType} from "../asn1.axdr/AxdrType";
import {ReverseByteArrayInputStream} from "../ReverseByteArrayInputStream";
import {ReverseByteArrayOutputStream} from "../ReverseByteArrayOutputStream";


export class OMD implements AxdrType{

    dataCode: Buffer | null = null;
    oi: Unsigned16 | null = null;
    mi: Unsigned8 | null = null;
    opm: Unsigned16 | null = null;

    constructor() {

    }

    set_dataCode(dataCode: Buffer) {
        this.dataCode = dataCode;
    }

    set_omd(oi: Unsigned16, mi: Unsigned8, opm: Unsigned16) {
        this.oi = oi;
        this.mi = mi;
        this.opm = opm;
    }

    decode(input: ReverseByteArrayInputStream): number {
        let codeLength = 0;

        this.oi = new Unsigned16();
        this.oi.set_const();
        codeLength += this.oi.decode(input);

        this.mi = new Unsigned8();
        this.mi.set_const();
        codeLength += this.mi.decode(input);

        this.opm = new Unsigned8();
        this.opm.set_const();
        codeLength += this.opm.decode(input);

        return codeLength;
    }

    encode(output: ReverseByteArrayOutputStream): number {
        let codeLength;

        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (let i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if (this.oi != null && this.mi != null && this.opm != null) {
                codeLength = 0;
                codeLength += this.opm.encode(output);
                codeLength += this.mi.encode(output);
                codeLength += this.oi.encode(output);
            }else{
                throw new Error("oi || mi || opm is null");
            }
        }
        return codeLength;
    }

    encodeAndSave(encodingSizeGuess: number) {
        let revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    toString(): string {
        if (this.oi != null && this.mi != null && this.opm != null) {
            return "sequence: {" + "oi: " + this.oi + ", mi: " + this.mi + ", opm: " + this.opm + "}";
        } else {
            return "oi || mi || opm is null";
        }
    }

}
